package com.fsd.admin.listener.activiti;

import com.fsd.admin.model.A_Employee;
import com.fsd.admin.model.Sys_PopedomAllocate;
import com.fsd.admin.model.Sys_PopedomGroup;
import com.fsd.admin.service.A_EmployeeService;
import com.fsd.admin.service.Sys_PopedomAllocateService;
import com.fsd.admin.service.Sys_PopedomGroupService;
import com.fsd.core.common.BusinessException;
import com.fsd.core.util.SpringContextHolder;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.delegate.DelegateTask;
import org.activiti.engine.delegate.TaskListener;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.impl.identity.Authentication;

/**
 * ================================
 * @Description: 用于指定流程的代理人任务监听器
 * @Author: lumingbao
 * @Date 2018-12-18 13:31
 * ================================
 */
public class AssigneeChooseTaskListener implements TaskListener{

    private ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();

    @Override
    public void notify(DelegateTask delegateTask) {
        try {
            Sys_PopedomGroupService popedomGroupService = (Sys_PopedomGroupService) SpringContextHolder.getBean("Sys_PopedomGroupServiceImpl");
            Sys_PopedomAllocateService popedomAllocateService = (Sys_PopedomAllocateService) SpringContextHolder.getBean("Sys_PopedomAllocateServiceImpl");

            String assignee = delegateTask.getAssignee();
            if("user".equals(assignee)){
                String userid = Authentication.getAuthenticatedUserId();
                if(userid == null || "".equals(userid)){
                    String processInstanceId = delegateTask.getExecution().getProcessInstanceId();
                    HistoricProcessInstance historicProcessInstance = processEngine.getHistoryService().createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
                    if(historicProcessInstance != null) {
                        userid = historicProcessInstance.getStartUserId();
                    }
                }
                if(userid == null || "".equals(userid)){
                    throw new BusinessException("流程发起人信息错误！");
                }
                delegateTask.setAssignee(userid);
            }else if("yxsh".equals(assignee)){
                String userid = Authentication.getAuthenticatedUserId();
                if(userid == null || "".equals(userid)){
                    String processInstanceId = delegateTask.getExecution().getProcessInstanceId();
                    HistoricProcessInstance historicProcessInstance = processEngine.getHistoryService().createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
                    if(historicProcessInstance != null) {
                        userid = historicProcessInstance.getStartUserId();
                    }
                }
                if(userid == null || "".equals(userid)){
                    throw new BusinessException("流程发起人信息错误！");
                }
                A_EmployeeService employeeService = (A_EmployeeService) SpringContextHolder.getBean("A_EmployeeServiceImpl");
                A_Employee inputUser = employeeService.get(userid);
                A_Employee admin = employeeService.getDepartMentAdminAcademyid(inputUser.getBranchid());
                if(admin == null){
                    throw new BusinessException("项目发起人所在院系未指定院系管理员，请先指定院系管理员");
                }
                delegateTask.setAssignee(admin.getId());
            }else if(assignee.length() == 5 && assignee.indexOf("js") != -1){
                // 角色编码
                String roleCode = assignee;
                // 通过角色编码查询角色信息
                Sys_PopedomGroup popedomgroup = popedomGroupService.getObjectByCode(roleCode);
                if(popedomgroup != null){
                    String roleId = popedomgroup.getId();
                    // 通过角色ID查询角色关联的用户ID
                    Sys_PopedomAllocate popedomallocate = popedomAllocateService.getObjectByPopedomIdAndType(roleId, "qxlxyh");
                    if(popedomallocate != null){
                        String userId = popedomallocate.getBelongid();
                        delegateTask.setAssignee(userId);
                    }else{
                        throw new BusinessException("流程绑定的角色没有关联的用户，请先完善用户授权");
                    }
                }else{
                    throw new BusinessException("流程关联的角色信息不存在，请先完善角色配置");
                }
            }
        }catch (Exception e){
            throw new RuntimeException(e.getMessage());
        }
    }
}
